//
//  RecommendViewController.m
//  XMJJ_zml
//
//  Created by 杨何华 on 2025/5/10.
//

#import "RecommendViewController.h"
#import "WaterfallFlowLayout.h"
#import "CustomCollectionViewCell.h"
#import "ZMYTabBar.h"
#import "CityViewController.h"
#import "RoundedSearchBar.h"
#import "ZMYCommend.h"
#import "XMLoginOtherPhoneController.h"
#import "SDWebImageManager.h"
#import <Photos/Photos.h>
@interface RecommendViewController ()<UICollectionViewDataSource, WaterfallFlowLayoutDelegate,ZMYTabBarDelegate>

@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) NSArray<NSString *> *tabTitles;
@property (nonatomic, assign) NSInteger selectedTabIndex;
@property (nonatomic, strong) NSMutableArray<NSArray *> *dataSources; // 存储不同标签对应数据源
@property (nonatomic, strong) ZMYTabBar *tabBar;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) NSArray<UIView *> *contentPages;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSArray<NSNumber *> *imageHeights;
@property (nonatomic, strong) RoundedSearchBar *searchBar;
@property (nonatomic, strong) UIView *outSizeView;


@property (nonatomic, strong) NSMutableArray * dataArray;
@property (nonatomic, strong) NSMutableDictionary<NSString *, NSValue *> *imageSizeCache; // 缓存图片尺寸
@end

@implementation RecommendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = kColorHEX(0xF6F6F6);
//    self.dataArray = [NSMutableArray array];

// 初始化标签标题
 
    [self setupTabBar];
    [self setupLocation];

    [self getRecommendServiceNologin:getRecommendService];
 
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
}

- (void)requestPhotoLibraryAccess {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) {
                [self fetchAssets];
            } else {
                NSLog(@"用户拒绝了访问相册的权限");
            }
        }];
    } else if (status == PHAuthorizationStatusAuthorized) {
        [self fetchAssets];
    } else {
        NSLog(@"用户拒绝了访问相册的权限");
    }
}

- (void)fetchAssets {
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
    
    // 获取所有的照片和视频资源
    PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsWithOptions:options];
    for (PHAsset *asset in assets) {
        // 检查资源类型
        if (asset.mediaType == PHAssetMediaTypeImage) {
            NSLog(@"这是一张照片，文件名：%@", asset.localIdentifier);
        } else if (asset.mediaType == PHAssetMediaTypeVideo) {
            NSLog(@"这是一个视频，文件名：%@", asset.localIdentifier);
        }
    }
}

- (void)getRecommendServiceNologin:(NSString *) param{
    NSMutableArray * array = [NSMutableArray array];
    [[XMNetwork shareInstance] postDataWithPath:[NSString stringWithFormat:@"%@%@", HttpInterface, param] parameters:@{@"pageNum":@"1",@"pageSize":@"1"}.mutableCopy needToken:NO headers:@{@"tenant-id":@"1"} success:^(id  _Nonnull responseObject) {
        NSDictionary * resultDic = responseObject;
        NSArray * data = [resultDic objectForKey:@"data"];
        for (NSDictionary * json in data ) {
            ZMYCommend *zmyCommend = [ZMYCommend yy_modelWithJSON:json];
//            zmyCommend.coverImageUrl = @"https://imgessl.kugou.com/stdmusic/20191210/20191210163806402555.jpg";
            NSLog(@"%@",zmyCommend);
            [array  addObject:zmyCommend];
        }
        self.dataArray = array;
        [self.collectionView reloadData];
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"%@",error.description);
        
    }];
}

- (void)setupTabBar {
    NSArray *tabTitles = @[@"推荐", @"关注", @"同城"];
    
    UIView * outSizeView = [[UIView alloc] initWithFrame:CGRectMake(0, 60, self.view.bounds.size.width, 44)];
    [self.navigationController.view addSubview:outSizeView];
    outSizeView.backgroundColor = [UIColor whiteColor];
    self.outSizeView = outSizeView;
    self.tabBar = [[ZMYTabBar alloc] initWithFrame:CGRectMake(90, 0, self.view.bounds.size.width-180, 44) titles:tabTitles];
    self.tabBar.delegate = self;
    [outSizeView addSubview:self.tabBar];
    
         self.imageHeights = @[@(100), @(200), @(150), @(250), @(120), @(180), @(220), @(160)];
          // 创建自定义布局
          WaterfallFlowLayout *layout = [[WaterfallFlowLayout alloc] init];
          layout.delegate = self;
          layout.columnCount = 2;
          layout.columnSpacing = 10;
          layout.rowSpacing = 10;
          layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
          // 创建 UICollectionView
          self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, outSizeView.height + outSizeView.y, self.view.bounds.size.width, self.view.bounds.size.height - outSizeView.height  - outSizeView.y) collectionViewLayout:layout];
          self.collectionView.dataSource = self;
          self.collectionView.backgroundColor = [UIColor clearColor];
          [self.collectionView registerClass:[CustomCollectionViewCell class] forCellWithReuseIdentifier:@"Cell"];
          [self.view addSubview:self.collectionView];
        layout.sectionInset = UIEdgeInsetsMake(0, layout.sectionInset.left, layout.sectionInset.bottom, layout.sectionInset.right);

}
 
- (void)setupLocation {
    UIView * searchView = [UIView new];
    searchView.frame = CGRectMake(0, 0, 40, 40);
    [self.outSizeView addSubview:searchView];
     UIButton * searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    searchButton.frame =CGRectMake(10, 0, 40, 40);
    searchButton.titleLabel.font = [UIFont systemFontOfSize:13];
    [searchButton setImage:[UIImage imageNamed:@"search_remend"] forState:UIControlStateNormal];
    [searchView addSubview:searchButton];
    
    
    UIButton * cameButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cameButton.frame =CGRectMake(self.outSizeView.bounds.size.width-60, 0, 40, 40);
    cameButton.titleLabel.font = [UIFont systemFontOfSize:13];
    [cameButton setImage:[UIImage imageNamed:@"came"] forState:UIControlStateNormal];
    [self.outSizeView addSubview:cameButton];
    [cameButton addTarget:self action:@selector(requestPhotoLibraryAccess) forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CustomCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
//    cell.backgroundColor = [UIColor lightGrayColor]; // 这里用灰色背景代替实际图片
    cell.data = self.dataArray[indexPath.row];
    return cell;
}

#pragma mark - WaterfallFlowLayoutDelegate


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout heightForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZMYCommend *  zmyCommend = self.dataArray[indexPath.item];
    // 计算单行文本宽度
    NSString *text = zmyCommend.title;
    UIFont *font = [UIFont systemFontOfSize:15.0];
     // 计算多行文本高度
    CGSize maxSize = CGSizeMake(300, CGFLOAT_MAX);
    CGRect rect = [text boundingRectWithSize:maxSize
                                     options:NSStringDrawingUsesLineFragmentOrigin
                                  attributes:@{NSFontAttributeName: font}
                                     context:nil];
    CGFloat height = rect.size.height;

     return 200 + height + 100; // 默认占位尺寸
 

}
- (void)ZMYTabBar:(nonnull ZMYTabBar *)tabBar didSelectTabAtIndex:(NSInteger)index {
    if (index == 0){
        [self getRecommendServiceNologin:getRecommendUGCNologin];
    }
    else if (index == 1) {
        NSString *  accessToken = [[XMUserManager shareInstance] getUser].accessToken;
        if (accessToken) {
            [self getRecommendServiceNologin:getFindAttentionUrl];
        }
        else {
            XMLoginOtherPhoneController * loginVc = [XMLoginOtherPhoneController new];
            loginVc.modalPresentationStyle =  UIModalPresentationFullScreen;
            [self presentViewController:loginVc animated:YES completion:nil];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController dismissViewControllerAnimated:YES completion:nil];
            });
        }
    }
    else {
        [self getRecommendServiceNologin:getCurrentCity];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
